package oss

import (
	"context"
	"encoding/json"
	"github.com/tencentyun/cos-go-sdk-v5"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"
)

type TencentOss struct {
	Bucket    string
	Region    string
	SecretId  string
	SecretKey string
	Schema    string
}

func NewTencentOss(config string) *TencentOss {
	var tencentOss TencentOss
	json.Unmarshal([]byte(config), &tencentOss)
	return &tencentOss
}

// 上传
func (p TencentOss) Upload(file *multipart.FileHeader, key string) string {
	client := p.NewClient()
	f, openError := file.Open()
	if openError != nil {
		panic(openError)
	}
	defer f.Close()

	_, err := client.Object.Put(context.Background(), strings.TrimLeft(key, "/"), f, nil)
	if err != nil {
		panic(err)
	}
	return p.Schema + "://" + p.Bucket + "." + "cos." + p.Region + ".myqcloud.com" + key
}

// 删除
func (p TencentOss) DeleteFile(key string) error {
	client := p.NewClient()
	name := strings.TrimLeft(key, "/")
	_, err := client.Object.Delete(context.Background(), name)
	if err != nil {
		panic(err)
	}
	return nil
}

// 获取链接
func (p TencentOss) NewClient() *cos.Client {
	urlStr, _ := url.Parse(p.Schema + "://" + p.Bucket + ".cos." + p.Region + ".myqcloud.com")
	baseURL := &cos.BaseURL{BucketURL: urlStr}
	client := cos.NewClient(baseURL, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  p.SecretId,
			SecretKey: p.SecretKey,
		},
	})
	return client
}

// 获取客户端上传配置信息
func (p TencentOss) GetCliendConfig(key string) map[string]interface{} {
	data := map[string]interface{}{
		"SecretId":  p.SecretId,
		"SecretKey": p.SecretKey,
		"Bucket":    p.Bucket,
		"Schema":    p.Schema,
		"Region":    p.Region,
		"key":       key,
		"type":      "tencent",
	}
	return data
}
